# 存储订单, 相关需求单状态变为采购中
import sys
sys.path.append("..")
import json
from flask import request
from create_id import get_id
from db_client import *

def store_order():
    token = request.headers.get('token')
    flag, right = token_client.check_token(token)
    if not flag:
        t = {
            'state': 'false',
            'msg': '无权限, 存储订单单失败'
        }
        return json.dumps(t, ensure_ascii=False)
    else:
        data = json.loads(request.get_data())
        supplier_id = data['supplier_id']
        item_id = data['item_id']
        purchase = data['purchase_quantity']
        accepted = data['accepted_quantity']
        unit_price = data['unit_price']
        total_price = data['total_price']
        plan_id = data['plan_id']
        _id = get_id('DD')
        # state = '采购中'

        flag2 = mysql_client.store_order(_id, supplier_id, item_id, purchase, accepted, unit_price, total_price, plan_id)
        if flag2:
            t = {
                'state': 'true',
                'msg': 'success'
            }

            # 更新相关需求单状态为 采购中
            demand_ids = mysql_client.search_demands_of_plan(plan_id)
            demand_ids = demand_ids.split(',')
            for demand_id in demand_ids:
                data = {
                    'de_if': '采购中'
                }
                mysql_client.update_demand(data, demand_id)

            return json.dumps(t, ensure_ascii=False)
        else:
            t = {
                'state': 'false',
                'msg': '存储订单失败'
            }
            return json.dumps(t, ensure_ascii=False)
            